<?php
include_once('includes/survey_meta.php');

function output_stepwise() {
	ob_start();
	$next_str = __('Next >>', 'wp-surveys');
	$previous_str = __('<< Previous', 'wp-surveys');
	$finish_str = __('Finish ->', 'wp-surveys');
	$no_answer_text = __('No answer given. All questions must be answered.', 'wp-surveys');

	wp_register_script('wp-surveys-stepwise', SURVEYS_ABS_URL_PATH . '/js/wp-surveys-stepwise.js', array('jquery'));
	wp_print_scripts('wp-surveys-stepwise');	
?>
<script type="text/javascript">
jQuery(document).ready(function() {
	wp_surveys_navigation_data.next_label = '<?php echo $next_str;?>';
	wp_surveys_navigation_data.previous_label = '<?php echo $previous_str;?>'; 
	wp_surveys_navigation_data.finish_label = '<?php echo $finish_str;?>';
	wp_surveys_navigation_data.no_answer_text = '<?php echo $no_answer_text;?>';
});
	
var wp_surveys_step_navigation_HTML = new Array(
	'<div class="wp_survey_navigate_div">',
	'	<form action="" method="POST">',
	'		<table width="100%" border="0" cellspacing="0" cellpadding="0">',
	'			<tr>',
	'				<td class="wp_surveys_navigate_button_div wp_surveys_navigate_button_previous_div" align="right" width="50%"><input type="button" id="wp_surveys_navigate_previous" name="wp_surveys_navigate_previous" class="wp_surveys_navigate_button wp_surveys_navigate_previous" value="<?php echo $previous_str?>" onClick="wp_surveys_previous_step()"/></td>',
	'				<td class="wp_surveys_navigate_button_div wp_surveys_navigate_button_next_div" align="left" width="50%"><input type="button" id="wp_surveys_navigate_next" name="wp_surveys_navigate_next" class="wp_surveys_navigate_button wp_surveys_navigate_next" value="<?php echo $next_str?>" onClick="wp_surveys_next_step()"/></td>',
	'			</tr>',	
	'		</table>',
	'	</form>',
	'</div>'
);
</script>
<?php
	$output = ob_get_contents();
	ob_end_clean();
	return $output;
}

function output_default_css() {
	return '<style type="text/css">@import url("'.SURVEYS_ABS_URL_PATH.'/css/wp-surveys.css");</style>';
}

function db_get_template ($survey_id, &$tpl_source, &$smarty_obj)
{
    // do database call here to fetch your template,
    // populating $tpl_source
    $tpl_source = stripcslashes(stripcslashes(get_survey_meta($survey_id, 'user_report')));
    return true;
}

function db_get_timestamp($survey_id, &$tpl_timestamp, &$smarty_obj)
{
    $tpl_timestamp = '';
    return true;
}

function db_get_secure($tpl_name, &$smarty_obj)
{
    // assume all templates are secure
    return true;
}

function db_get_trusted($tpl_name, &$smarty_obj)
{
    // not used for templates
}

function output_survey($survey_id) {
	global $wpdb, $current_user, $wp_surveys_tables;

	require_once('functions.php');
	
	ob_start();

	$open = $wpdb->get_var("SELECT `survey_open` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
	$no_repost = get_survey_meta($survey_id, 'no_repost') == 'true';
	$has_posted = $wpdb->get_var("SELECT count(`response_id`) FROM `".$wp_surveys_tables['response']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");

	if(!$open) {
?>
		<div class="wp_survey_closed"><?php echo __('Sorry, this survey is no longer open.', 'wp-surveys');?></div>
<?php	
	}

	
	if($_POST['wpsurveys_button'] == __('Submit Survey', 'wp-surveys') && $_SESSION['voted']) {
		wp_register_script('trimpath-template', SURVEYS_ABS_URL_PATH . '/js/trimpath-template.js');
		wp_print_scripts('trimpath-template');
?>
		<div class="wp_survey_completed"><?php echo __('Thank you for completing our survey!', 'wp-surveys');?></div>
<?php
		$user_report_type = get_survey_meta($survey_id, 'user_report_type');
		$user_report = get_survey_meta($survey_id, 'user_report');
		
		if ($user_report && $user_report != '' &&
		 $user_report_type != 'none') {
			require 'Smarty/libs/Smarty.class.php';

			$smarty = new Smarty;
			
			$smarty->compile_check = true;
			$smarty->clear_compiled_tpl('db:'.$survey_id); 
			$smarty->debugging = false;
			
			// register the resource name "db"
			$smarty->register_resource("db", array("db_get_template",
			                                       "db_get_timestamp",
			                                       "db_get_secure",
			                                       "db_get_trusted"));

			ob_start();
			
			assign_smarty_data($_SESSION['response_id'], $smarty);
			$smarty->display('db:'.$survey_id);
			$output = ob_get_contents();

			ob_end_clean();

			if ($user_report_type == 'html' || $user_report_type == 'both') {
?>
		<div class="wp_survey_report"><?php echo $output;?></div>
<?php
			}
	
			if ($user_report_type == 'email' || $user_report_type == 'both') {
				$user_sql = 
						"SELECT distinct".
						"	u.user_email ".
						
						"FROM ".
						"	".$wp_surveys_tables['response']." r ".
						"	INNER JOIN ".$wp_surveys_tables['user']." u ON u.ID = r.user_id ".
			
						"WHERE ".
						"	r.response_id=".$_SESSION['response_id'];
				$user_email = $wpdb->get_var($user_sql);

				$admin_email = get_option( "admin_email" );

				$from_name = get_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_option( "site_name" ) );
				$message_headers = 	"MIME-Version: 1.0\r\n" . 
									"From: \"{$from_name}\" <{$admin_email}>\r\n" . 
									"Content-Type: text/html; charset=\"".get_option('blog_charset')."\";\r\n";

				$subject = '[' . $from_name . '] ' . __('Survey Report.', 'wp-surveys');

				try {
					// wp_mail didn't want to work - time constraints forced me to use php's mail()
					//$emailed = wp_mail($user_email, $subject, $output, $message_headers);
					$emailed = mail($user_email, $subject, $output, $message_headers); //mail command :)	
				} catch (Exception $e) {
					//don't know why this doesn't work.
					echo 'Failed to send mail. '.$e->getMessage();
				}
			}
		}
		$_SESSION['response_id'] = null;
		$_SESSION['voted'] = false;
	}
	
	if ($has_posted && $no_repost) {
?>
		<div class="wp_survey_no_repost"><?php echo __('This survey may only be completed once.', 'wp-surveys');?></div>
<?php 
	}	
	
	if ($has_posted && !$no_repost && $_POST['wpsurveys_button'] != __('Submit Survey', 'wp-surveys')) {
?>
		<div class="wp_survey_has_posted"><?php echo __('This survey has already been completed.', 'wp-surveys');?></div>
<?php 
	}	
	
	if ($_SESSION['novote'] == true) {
?>
		<div class="wp_survey_no_vote"><?php echo __('All answers must be completed.', 'wp-surveys');?></div>
<?php 
	}	
?>
		<div class="wp_survey_messages"></div>
<?php 
	
	if (!($has_posted && $no_repost) && $open) {
		$current_plugins = get_option('active_plugins');
		if ((file_exists(ABSPATH . PLUGINDIR . '/polyglot.php')) && (in_array('polyglot.php', $current_plugins)))
			$polyglot = true;
		$surveys = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;",ARRAY_A);
		if (sizeof($surveys)>0) foreach ($surveys as $survey) {
			$questions = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['question']."` WHERE `survey_id`='".$survey['survey_id']."';",ARRAY_A);
?>
	<div class="wp_survey">
		<div class="wp_survey_info">
			<div class="wp_survey_name"><?php print($polyglot?stripcslashes(polyglot_filter($survey['survey_name'])):stripcslashes($survey['survey_name']));?></div>
			<div class="wp_survey_describe"><?php print($polyglot?stripcslashes(polyglot_filter($survey['survey_describe'])):stripcslashes($survey['survey_describe']));?></div>
		</div>
	
		<br />

<?php
			if($questions) {
?>
		<form id="wp_survey_form" action="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" method="post">
<?php
				$q = 1;
				if (sizeof($questions)>0) foreach($questions as $question) {
					$answers = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['answer']."` WHERE `question_id`=".$question['question_id'].";",ARRAY_A);
					//unset($extra_options);
?>
			<div id="wp_survey_question_<?php echo $q;?>" class="wp_survey_question_info<?php echo $question['question_group'] != '' ? (' wp_survey_question_group_'.str_replace('-', '_', sanitize_title($question['question_group']))) : '';?>">
				<input type="hidden" id="wp_survey_question_<?php echo $q;?>_id" value="<?php echo $question['question_id'];?>"/>
				<div class="wp_survey_question"><span class="wp_survey_question_number"><?php echo $q;?>. </span><?php print($polyglot?stripcslashes(polyglot_filter($question['question_text'])):stripcslashes($question['question_text']));?></div>
<?php
					// Define types of questions
					if($question['question_type']=="one-vert") {
						//$forever = $question['question_forever'];  
						//if($forever != '')
							//$extra_options = explode(",", $forever);
						$a = 1;
						if (sizeof($answers) > 0) foreach ($answers as $answer) {
?>
				<span class="wp_survey_answer wp_survey_answer_vertical">
					<table cellspacing="0" cellpadding="0" border="0">
						<tr>
							<td class="wp_survey_answer_input_td" vAlign="top">
								<span class="wp_survey_answer_number"><?php echo $a;?>. </span><input type="radio" id="answer_<?php echo $answer['answer_id'];?>" class="answer_<?php echo $question['question_id'];?>" name="answer_<?php echo $question['question_id'];?>" value="<?php echo $answer['answer_id'];?>" <?php echo $_POST['answer_'.$question['question_id']] == $answer['answer_id'] ? ' checked="checked"' : '';?>/>
							</td>
							<td class="wp_survey_answer_label_td">
								<label for="answer_<?php echo $answer['answer_id'];?>"><?php print($polyglot?stripcslashes(polyglot_filter($answer['answer_text'])):stripcslashes($answer['answer_text']));?></label>
							</td>
						</tr>
					</table>
				</span>
<?php
							$a++;
						}
						/*if(isset($extra_options)) {
							foreach($extra_options as $option) {
								print("<input type='radio' ");
								print(" name=\"option[".$question['question_id']."][".$q."]\"value=\"".$option."\">&nbsp;");
								print(trim( stripcslashes ($option) )."\n");
							}
						}*/
?>
				<br />
<?php
	
					} elseif($question['question_type']=="one-hori") {
						//$forever=$question['question_forever'];  
						//if($forever != '')
							//$extra_options = explode(",", $forever);
?>
				<br />
<?php
						$a = 1;
						if (sizeof($answers) > 0) foreach ($answers as $answer) {
?>
				<span class="wp_survey_answer wp_survey_answer_horizontal">
					<br />
					<span class="wp_survey_answer_number"><?php echo $a;?>. </span><input type="radio" name="answer_<?php echo $question['question_id'];?>" value="<?php echo $answer['answer_id'];?>" <?php echo $_POST['answer_'.$question['question_id']] == $answer['$answer_id'] ? ' checked="checked"' : '';?>/>
					&nbsp;
					<?php print($polyglot?stripcslashes(polyglot_filter($answer['answer_text'])):stripcslashes($answer['answer_text']));?>
					&nbsp;
					&nbsp;
					<br />
				</span>
<?php
							$a++;
						}
						/*if(isset($extra_options)) {
							foreach($extra_options as $option) {
								print("<input type='radio' ");
								print(" name=\"option[".$question['question_id']."][".$q."]\" value=\"".$option."\">&nbsp;");
								print(trim( stripcslashes ($option) )."&nbsp;&nbsp;\n");
							}
						}*/
?>
				<br />
<?php			
					} elseif($question['question_type']=="one-menu") {
						//$forever=$question['question_forever'];  
						//if($forever != '')
							//$extra_options = explode(",", $forever);
?>
				<br />
				<select class="wp_survey_answer wp_survey_answer_menu" name="answer_<?php echo $question['question_id'];?>" style="width:90%">
					<option value="<?php echo __('No response recorded', 'wp-surveys');?>">-- <?php echo __('Select an answer below', 'wp-surveys');?></option>
<?php				
						if (sizeof($answers) > 0) foreach ($answers as $answer) {
?>
					<option value="<?php echo $answer['answer_id'];?>" <?php echo $_POST['answer_'.$question['question_id']] == $answer['answer_id'] ? ' selected="selected">' : '';?>>
						<?php echo $polyglot ? stripcslashes(polyglot_filter($answer['answer_text'])) : stripcslashes($answer['answer_text']);?> 		
					</option>
<?php
						}
						/*if(isset($extra_options)) {
							foreach($extra_options as $option) {
								print("<option value=\"".trim($option)."\" ");
								print(" >");
								print("".trim( stripcslashes ($option) )."</option>\n");
							}
						}*/
?>
				</select>
				<br />
<?php
					}
					/*if($question['question_type']=="mul-vert") {
						$running = 0;
						//$forever = $question['question_forever'];
						//if($forever != '')
							//$extra_options = explode(",", $forever);
						for($q=0;$q<10;$q++) { 
							$option="question_option_".$q;
							if($question[$option]!='') {
								print("<input type='checkbox' ");
								print(" name=\"option[".$question['question_id']."][".$running."]\" value=\"".$question[$option]."\">&nbsp;");
								print(stripcslashes ( $question[$option] )."\n");  
								$running++;
								}
							}
						if(isset($extra_options)) {
							foreach($extra_options as $options) {
								$q++;
								print("<input type='checkbox' ");
								print(" name='option[".$question['question_id']."][".$running."]' value='".trim( $options )."'>&nbsp;");
								print(trim( stripcslashes ($options) )."\n");        
								$running++;
								}
							}
						}
					if($question['question_type']=="mul-hori") {
						$forever=$question['question_forever'];  
						$running=0;
						if($forever != "")
							$extra_options = explode(",", $forever);
						print("<p>\n");
						for($q=0;$q<10;$q++) { 
							$option="question_option_".$q;
							if($question[$option]!='') {
								print("<input type='checkbox' ");
								print(" name='option[".$question['question_id']."][".$running."]' value='".$question[$option]."'>&nbsp;");
								print(stripcslashes ( $question[$option] )."&nbsp;&nbsp;\n");   
								$running++;
								}
							}
						if(isset($extra_options)) {
							foreach($extra_options as $options) {
								print("<input type='checkbox' ");
								print(" name='option[".$question['question_id']."][".$running."]' value='".trim( $options )."'>&nbsp;");
								print(trim( stripcslashes ($options) )."&nbsp;&nbsp;\n");  
								$running++;
								}
							}
						print("\n\n");
						}
					elseif($question['question_type']=="open-onep") {
						print("<div class=\"wpsurveys_text\"><input name='option[".$question['question_id']."][0]' style=\"height:30px\" value='".$filled."'></div>\n");
						}
					elseif($question['question_type']=="open-more") {
						print("<div class=\"wpsurveys_text\"><input name='option[".$question['question_id']."][0]' style=\"height:100px\" value='".$filled."'></div>\n");
						}
					else if($question['question_type']=="open-essa") {
						print("<div class=\"wpsurveys_text\"><input name='option[".$question['question_id']."][0]' style=\"height:200px\" value='".$filled."'></div>\n");
						}
					elseif($question['question_type']=="open-date") {
						print("<div class=\"wpsurveys_text\"><input name='option[".$question['question_id']."][0]' style=\"height:300px\" value='".$filled."'></div>\n");
						}*/
					//else print("Undefined.");
?>
			</div>
<?php
					$q++;
				}
?>
			<input type="hidden" id="question_count" value="<?php echo ($q-1);?>" />
			<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
			<input type="hidden" name="wpsurveys_button" value="<?php echo __('Submit Survey', 'wp-surveys');?>"/>
			<div class="wp_survey_submit_div">
				<input type="submit" name="wpsurveys_submit_button" value="<?php echo __('Submit Survey', 'wp-surveys');?>" class="wp_survey_submit" />
			</div>
		</form>
<?php
			} else { 
?>
		<div class="wp_survey_no_questions"><?php echo __('This survey has no questions yet.', 'wp-surveys');?></div>
<?php 
			}
?>
	</div>
<?php
		}
	}
	$output = ob_get_contents();
	ob_end_clean();
	return $output;
}	
?>